package main

import (
	"encoding/hex"
	"fmt"
	"github.com/tarm/serial"
	"log"
	"strconv"
	"time"
)

func main() {
	ser := &serial.Config{Name: "COM5", Baud: 9600, Size: 8, ReadTimeout: time.Second * 10}
	//打开串口
	conn, err := serial.OpenPort(ser)
	if err != nil {
		fmt.Println("串口初始化错误")
		log.Fatal(err)
	}
	fmt.Println("………………………………………………………串口初始化完成………………………………………………………")
	for {
		fmt.Println("………………………………………………………读取………………………………………………………")
		//获取设备ID指令
		readcommand := []byte{0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B}
		//读取温湿度指令
		_, err = conn.Write(readcommand)
		if err != nil {
			log.Println(err)
		}
		buf := make([]byte, 512)
		lens, err := conn.Read(buf)
		if err != nil {
			log.Println(err)
		}
		revData := buf[:lens]
		//读出的数据为16进制byte型，转为string型
		data := hex.EncodeToString(revData)
		fmt.Printf("接受到数据： %v  \n", data)

		if len(data) <= 4 {
			fmt.Println("数据读取错误")
			time.Sleep(2 * time.Second)
			continue
		}
		d := ""
		// win下截取0304开头字符串
		if data[:4] == "0304" {
			d = data[4:]
			Handler(d)
		}
		// linux下截取010304开头字符串
		if data[:6] == "010304" {
			d = data[6:]
			Handler(d)
		}
		time.Sleep(2 * time.Second)

	}

}

// Handler 格式化采集到的数据
func Handler(data string) error {
	//将16进制转换为10进制
	tem, err := strconv.ParseUint(data[:4], 16, 32)
	hum, err := strconv.ParseUint(data[4:8], 16, 32)

	tems := strconv.Itoa(int(tem))[:2] + "." + strconv.Itoa(int(tem))[2:]
	hums := strconv.Itoa(int(hum))[:2] + "." + strconv.Itoa(int(hum))[2:]

	fmt.Printf("采集到温度： %v ,湿度： %v \n", tems, hums)
	return err
}
